<template>
	<div>
		<el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/EquipmentType'}"><i class="el-icon-s-home" style="margin-right: 15px;font-size: 16px"></i>设备类型配置</el-breadcrumb-item>
      <el-breadcrumb-item v-if="this.$route.query.sign === 'add'"><i class="el-icon-menu" style="margin-right: 15px;font-size: 16px"></i>新增设备类型</el-breadcrumb-item>
      <el-breadcrumb-item v-if="this.$route.query.sign === 'edit'"><i class="el-icon-menu" style="margin-right: 15px;font-size: 16px"></i>编辑设备类型</el-breadcrumb-item>    
    </el-breadcrumb>
    <div class="info">
			<el-card shadow="always">
        <el-row style="border-left: 9px solid #6C59DD; padding-left: 15px;"><span style="font-size: 20px;color:#6C59DD">基础信息</span></el-row>
        <el-form :model="equipInfoForm" :rules="equipInfoFormRules" ref="equipInfoForm" label-width="130px" size="small" style="margin: 10px 40px 50px 20px">
            <el-col :span="8">
              <el-form-item label="设备类型：" prop="equipmName" :rules="equipInfoFormRules.equipmName">
                <el-input v-model.trim="equipInfoForm.equipmName" placeholder="请输入设备类型" clearable :disabled="$route.query.kind_name==='雷电冲击耐受电压试验设备' || $route.query.kind_name==='工频耐受电压试验设备' ? true : false"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="设备类型英文：" prop="workePosit" :rules="equipInfoFormRules.workePosit">
                <el-input v-model="equipInfoForm.workePosit" placeholder="请输入设备类型英文" clearable  :disabled="$route.query.kind_name==='雷电冲击耐受电压试验设备' || $route.query.kind_name==='工频耐受电压试验设备' ? true : false"></el-input>
              </el-form-item>
            </el-col>
        </el-form>
        <el-row style="margin-bottom: 20px">
          <el-button :disabled="btnList.add" type="primary" size="small" style="float: right;" @click="addCheckItems">新增设备参数</el-button>
        </el-row>
        <el-form :model="checkInfoForms" ref="checkInfoForms" :rules="checkInfoFormsRules" :inline-message="true" :validate-on-rule-change="false" size="small">
          <el-table :data="checkInfoForms.spotCheckInfo" @cell-dblclick="tableEditEquip" style="width: 100%">
            <el-table-column label="序号" type="index" width="120" align="center"></el-table-column>
            <el-table-column label="设备参数" align="center">
              <template slot-scope="scope">
                <el-form-item :prop="'spotCheckInfo.' + scope.$index + '.param_name'" :rules="checkInfoFormsRules.param_name">
                  <span v-if="scope.row.contentType === 'text'"> {{scope.row.param_name}}</span>
                  <el-input clearable v-if="scope.row.contentType === 'input'" v-model="scope.row.param_name" @blur="paramBlur(scope.row)" size="mini" placeholder="请输入设备参数"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="备注" align="center">
             <template slot-scope="scope">
                <el-form-item>
                  <span v-if="scope.row.remarkType === 'text' && scope.row.remark === ''"> --</span>
                  <span v-if="scope.row.remarkType === 'text' && scope.row.remark !== ''"> {{scope.row.remark}}</span>
                  <el-input clearable v-if="scope.row.remarkType === 'input'" v-model="scope.row.remark" @blur="scope.row.remarkType = 'text'" size="mini" placeholder="请输入备注"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center"  width="120">
              <template slot-scope="scope">
                <el-button type="text" :disabled="btnList.delete" @click="deleteInfos(scope.$index,scope.row)" style="color: #E83131;" size="small">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form>
			<!-- </el-card>
      <el-card shadow="always" class="checkInfoForm"> -->
        <el-row style="margin: 20px 0; border-left: 9px solid #6C59DD; padding-left: 5px;">
          <span style="font-size: 20px;color:#6C59DD; margin-left: 10px;">点检信息</span>
          <el-button :disabled="btnList.add" type="primary" size="small" style="float: right" @click="addCheckItem">新增点检内容</el-button>
        </el-row>
        <el-form :model="checkInfoForm" ref="checkInfoForm" :rules="checkInfoFormRules" :inline-message="true" :validate-on-rule-change="false" size="small">
          <el-table :data="checkInfoForm.spotCheckInfo" @cell-dblclick="tableEdit" style="width: 100%">
            <el-table-column label="序号" type="index" width="120" align="center"></el-table-column>
            <el-table-column label="点检内容" align="center">
              <template slot-scope="scope">
                <el-form-item :prop="'spotCheckInfo.' + scope.$index + '.item_name'" :rules="checkInfoFormRules.item_name">
                  <span v-if="scope.row.contentType === 'text'"> {{scope.row.item_name}}</span>
                  <el-input clearable v-if="scope.row.contentType === 'input'" v-model="scope.row.item_name" @blur="itemBlur(scope.row)" size="mini" placeholder="请输入点检内容"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="备注" align="center">
             <template slot-scope="scope">
                <el-form-item>
                  <span v-if="scope.row.remarkType === 'text' && scope.row.remark === ''"> --</span>
                  <span v-if="scope.row.remarkType === 'text' && scope.row.remark !== ''"> {{scope.row.remark}}</span>
                  <el-input clearable v-if="scope.row.remarkType === 'input'" v-model="scope.row.remark" @blur="scope.row.remarkType = 'text'" size="mini" placeholder="请输入备注"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center"  width="120">
              <template slot-scope="scope">
                <el-button type="text" :disabled="btnList.delete" @click="deleteInfo(scope.$index,scope.row)" style="color: #E83131;" size="small">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-form-item style="text-align:center;margin-top: 20px">
            <el-button type="primary" class="saveButton" @click="verify('equipInfoForm')" :disabled="btnList.save" style="width:140px;margin-left: 40px">保存</el-button>
          </el-form-item>
        </el-form>
      </el-card>
		</div>
	</div>
</template>
<script>
import sessionStorage from '../../public/storage.js';
export default {
	data() {
    var validateName = (rule, value, callback) => {
        let reg = /^[\u4e00-\u9fa5]{0,}$/
        if(!reg.test(value)){
            callback(new Error('类型名称只能为汉字！'));
        }
        callback();
      }
      var validateEnName = (rule, value, callback) => {
        let reg = /^[A-Za-z-\s]{0,}$/
        if(!reg.test(value)){
            callback(new Error('类型英文名称只能为字母、空格、中横线！'));
        }
        callback();
      }
		return {
      checkInfoFormsRules: {
        param_name:[{ required: true, message: '请输入设备参数', trigger: 'blur' }]
      },
      checkInfoFormRules: {
        item_name:[{ required: true, message: '请输入点检内容', trigger: 'blur' }]
      },
      btnList: {
        add: false,
        save: false,
        delete: false
      },
      testGjbList: [],
      equipInfoForm: {
        equipmName: '', // 设备名称
        workePosit: '', // 设备英文名称
      },
      equipAllParams: [],
      stationInfo: [], // 工位信息列表
      deleteCheckInfo: [],
      deleteCheckInfos: [],
      equipInfoFormRules: {
        equipmName: [
          { required: true, message: '请输入设备类型名称', trigger: 'blur' },
          { validator: validateName, trigger: 'blur' }
        ],
        workePosit: [
          { required: true, message: '请输入设备类型英文名称', trigger: 'blur' },
          { validator: validateEnName, trigger: 'blur' }
        ]
      },
      checkInfoForm: {
        spotCheckInfo: [],
      },
      checkInfoForms: {
        spotCheckInfo: [],
      }
		};
	},
	methods: {
    // 添加点检内容
    addCheckItem(){
      this.$refs.checkInfoForm.validate(valid => {
         if(!valid) {
           return
         }
         if(this.checkInfoForm.spotCheckInfo.length !== 0){
           this.checkInfoForm.spotCheckInfo[this.checkInfoForm.spotCheckInfo.length-1].remarkType = 'text'
         }
        this.checkInfoForm.spotCheckInfo.push({
          contentType: 'input',
          remarkType: 'input',
          item_name: '',
          remark: ''
        })
      })
    },
    // 添加点检内容
    addCheckItems(){
       this.$refs.checkInfoForms.validate(valid => {
         if(!valid) {
           return
         }
        if(this.checkInfoForms.spotCheckInfo.length !== 0){
          this.checkInfoForms.spotCheckInfo[this.checkInfoForms.spotCheckInfo.length-1].remarkType = 'text'
        }
         this.checkInfoForms.spotCheckInfo.push({
        contentType: 'input',
        remarkType: 'input',
        param_name: '',
        remark: ''
        })
       })
    },
    // 双击单元格进行编辑
    tableEdit(row, column){
        if (column.label === '点检内容') {
          row.contentType = 'input';
          if (row.item_name === '请击输入点检内容') {
            row.item_name = '';
          }
        } else {
          row.remarkType = 'input';
          if (row.remark === '请双击输入备注') {
            row.remark = '';
          }
        }
    },
    // 双击单元格进行编辑
    tableEditEquip(row, column){
        if (column.label === '设备参数') {
          row.contentType = 'input';
          if (row.param_name === '请双击输入设备参数') {
            row.param_name = '';
          }
        } else {
          row.remarkType = 'input';
          if (row.remark === '请双击输入备注') {
            row.remark = '';
          }
        }
    },
    paramBlur(row) {
      this.$refs.checkInfoForms.validate(valid => {
        console.log(valid);
        if(valid){
          row.contentType = 'text'
        }
      })  
    },
    itemBlur(row) {
      this.$refs.checkInfoForm.validate(valid => {
        console.log(valid);
        if(valid){
          row.contentType = 'text'
        }
      })  
    },
    //  删除点检信息
    deleteInfo(index,row){
      if (this.$route.query.sign === 'edit' && row.item_id !== undefined) { // 用于后台删除数据
        this.deleteCheckInfo.push({
          item_id: row.item_id
        })
      }
      this.$delete(this.checkInfoForm.spotCheckInfo, index);
    },
    deleteInfos(index,row){
      if (this.$route.query.sign === 'edit' && row.item_id !== undefined) { // 用于后台删除数据
        this.deleteCheckInfos.push({
          item_id: row.item_id
        })
      }
      this.$delete(this.checkInfoForms.spotCheckInfo, index);
    },
    // 保存点检信息
    a() { // 新增检测名称是否重复 
          let x;
          for(let i = 0; i<this.testGjbList.length; i++) {
              if(this.testGjbList[i].kind_name === this.equipInfoForm.equipmName){
                  x = 0
              }
              if(this.testGjbList[i].kind_en_name === this.equipInfoForm.workePosit){
                  x = 1
              }
          }
          return x
      },
      b(id) { // 编辑检测名称是否重复
          let y;
          for(let i = 0; i<this.testGjbList.length; i++) {
              if(this.testGjbList[i].kind_name === this.equipInfoForm.equipmName){
                  if(this.testGjbList[i].ik_id === id){
                      
                  }else{
                      y = 0
                  }
              }
              if(this.testGjbList[i].kind_en_name === this.equipInfoForm.workePosit){
                  if(this.testGjbList[i].ik_id === id){
                      
                  }else{
                      y = 1
                  }
              }
          }
          return y
      },
    async saveCheckInfo() {
      this.$message({ message: '正在保存修改!', type: 'success', duration: 1000 });
      let ret;
      if (this.$route.query.sign === 'edit') {
        let a = await this.b(this.$route.query.ik_id)
        if(a === 0){
          return this.$message.error('设备类型名称重复！')
        } else if(a === 1) {
          return this.$message.error('设备类型英文名称重复！')
        }
        ret = await this.$http.put("/instrument/updateInstrumentInfo",{instrumentId: this.$route.query.ik_id,equipmentType: this.equipInfoForm.equipmName, equipmentTypeEn: this.equipInfoForm.workePosit, instrumentParams: this.checkInfoForms.spotCheckInfo, checkItems: this.checkInfoForm.spotCheckInfo});
      } else {
        let a = await this.a()
        if(a === 0){
          return this.$message.error('设备类型名称重复！')
        } else if(a === 1) {
          return this.$message.error('设备类型英文名称重复！')
        }
        ret = await this.$http.post("/instrument/addInstrumentKind",{equipmentType: this.equipInfoForm.equipmName, equipmentTypeEn: this.equipInfoForm.workePosit, instrumentParams: this.checkInfoForms.spotCheckInfo, checkItems: this.checkInfoForm.spotCheckInfo});
      }
      if(ret.code === 200){
        this.$message({ message: '保存成功!', type: 'success', duration: 1000 });
        this.$router.push({
          path: '/EquipmentType',
        });
      }
    },
    //验证
    verify(formName){
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$refs.checkInfoForms.validate(valid => {
            if(valid) {
              this.$refs.checkInfoForm.validate(valid => {
                if(valid) {
                  this.saveCheckInfo();
                }
              })
            }
          })
        }
      });
    },
    async roleBtnList () {
      const role_id = JSON.parse(sessionStorage.getItem('userInfo')).role_id;
      if(role_id){
        // 获取按钮权限状态
        let arr = await roleBtn.roleBtnList(role_id, this.menuId);
        this.btnList = arr;
      }
    }
	},
	async mounted() {
      if(this.$route.query.sign === 'edit') {
        this.equipInfoForm.equipmName = this.$route.query.kind_name // 设备名称
        this.equipInfoForm.workePosit = this.$route.query.kind_en_name // 设备英文名称
        let { result } = await this.$http.get(`/instrument/getInstrumentParams?instrumentId=${this.$route.query.ik_id}`)
        result.forEach(item => {
          item.contentType = 'text'
          item.remarkType = 'text'
        })
        this.checkInfoForms.spotCheckInfo = result
        let { result: res } = await this.$http.get(`/instrument/getCheckItems?instrumentId=${this.$route.query.ik_id}`)
        res.forEach(item => {
          item.contentType = 'text'
          item.remarkType = 'text'
        })
        this.checkInfoForm.spotCheckInfo = res

    }
	},
  async created() {
    const { result } = await this.$http.get('/instrument/getInstrumentKind')
    this.testGjbList = result
  }
};
</script>
<style lang="scss" scoped>
@import "./AddEquipment.scss";
</style>